package com.example.stuwork.service.impl;

import com.example.stuwork.common.Result;
import com.example.stuwork.dao.AdminDao;
import com.example.stuwork.dao.ClassDao;
import com.example.stuwork.dao.StudentDao;
import com.example.stuwork.dao.TeacherDao;
import com.example.stuwork.pojo.Admin;
import com.example.stuwork.pojo.Student;
import com.example.stuwork.pojo.Teacher;
import com.example.stuwork.service.AuthService;
import com.example.stuwork.service.AssignmentAllocationService;
import com.example.stuwork.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证服务实现类
 */
@Service
public class AuthServiceImpl implements AuthService {

    private static final Logger logger = LoggerFactory.getLogger(AuthServiceImpl.class);

    @Autowired
    private AdminDao adminDao;

    @Autowired
    private TeacherDao teacherDao;

    @Autowired
    private StudentDao studentDao;

    @Autowired
    private ClassDao classDao;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private AssignmentAllocationService assignmentAllocationService;

    /**
     * 管理员登录
     *
     * @param username 用户名
     * @param password 密码
     * @return 登录结果，成功返回token和用户信息
     */
    @Override
    public Result<?> adminLogin(String username, String password) {
        Admin admin = adminDao.getByUsername(username);
        if (admin == null) {
            return Result.error("用户名不存在");
        }

        // 验证密码
        if (!password.equals(admin.getPassword())) {
            return Result.error("密码错误");
        }

        // 生成JWT令牌
        String token = jwtUtil.generateToken(username, "admin", admin.getAdminId());

        // 返回结果
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("userInfo", admin);
        
        return Result.success(data);
    }

    /**
     * 教师登录
     *
     * @param teacherId 教师工号
     * @param password  密码
     * @return 登录结果，成功返回token和用户信息
     */
    @Override
    public Result<?> teacherLogin(String teacherId, String password) {
        Teacher teacher = teacherDao.getById(teacherId);
        if (teacher == null) {
            return Result.error("工号不存在");
        }

        // 验证密码
        if (!password.equals(teacher.getPassword())) {
            return Result.error("密码错误");
        }

        // 生成JWT令牌
        String token = jwtUtil.generateToken(teacherId, "teacher", teacherId);

        // 返回结果
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("userInfo", teacher);
        
        return Result.success(data);
    }

    /**
     * 学生登录
     *
     * @param studentId 学号
     * @param password  密码
     * @return 登录结果，成功返回token和用户信息
     */
    @Override
    public Result<?> studentLogin(String studentId, String password) {
        Student student = studentDao.findStudentById(studentId);
        if (student == null) {
            return Result.error("学号不存在");
        }

        // 验证密码
        if (!password.equals(student.getPassword())) {
            return Result.error("密码错误");
        }

        // 生成JWT令牌
        String token = jwtUtil.generateToken(studentId, "student", studentId);

        // 返回结果，不返回密码
        student.setPassword(null);
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("userInfo", student);
        
        return Result.success(data);
    }

    /**
     * 学生注册
     *
     * @param studentId 学号
     * @param name      姓名
     * @param gender    性别
     * @param password  密码
     * @param email     邮箱
     * @param phone     手机号
     * @param year      入学年份
     * @param deptNumber 院系编号
     * @param classId   班级ID
     * @return 注册结果
     */
    @Override
    public Result<?> studentRegister(String studentId, String name, String gender, String password, String email, String phone,
                                   String year, String deptNumber, Long classId) {
        // 检查学号是否已存在
        Student existingStudent = studentDao.findStudentById(studentId);
        if (existingStudent != null) {
            return Result.error("学号已存在");
        }

        // 创建学生对象
        Student student = new Student();
        student.setStudentId(studentId);
        student.setName(name);
        student.setPassword(password);
        student.setEmail(email);
        student.setPhone(phone);
        
        // 设置性别
        if (gender != null && !gender.isEmpty()) {
            student.setGender(gender);
        } else {
            student.setGender("男");  // 默认值
        }
        
        // 设置入学年份
        if (year != null && !year.isEmpty()) {
            student.setYear(year);
        } else {
            student.setYear("2024");  // 默认使用当前年份
        }
        
        // 设置院系编号
        if (deptNumber != null && !deptNumber.isEmpty()) {
            student.setDeptNumber(deptNumber);
        } else {
            student.setDeptNumber("未分配");
        }
        
        // 设置班级ID
        if (classId != null && classId > 0) {
            student.setClassId(classId);
            
            // 从班级信息中获取专业编码
            try {
                // 调用ClassDao获取班级信息
                com.example.stuwork.pojo.Class classInfo = classDao.getById(classId);
                if (classInfo != null && classInfo.getMajorCode() != null) {
                    // 设置专业编码为班级的专业编码
                    student.setMajorCode(classInfo.getMajorCode());
                } else {
                    student.setMajorCode("未分配");
                }
            } catch (Exception e) {
                // 发生异常时设置为未分配
                student.setMajorCode("未分配");
            }
        } else {
            student.setClassId(0L);    // 0表示未分配班级
            student.setMajorCode("未分配");
        }

        // 添加学生
        try {
            studentDao.addStudent(student);
            // 如果学生已指定班级，同步该班级的作业分配
            if (classId != null && classId > 0) {
                // 同步班级作业到新学生
                Result<Boolean> syncResult = assignmentAllocationService.syncAssignmentsForNewStudent(studentId, classId);
                if (!syncResult.isSuccess()) {
                    logger.warn("为新学生{}同步作业分配失败: {}", studentId, syncResult.getMessage());
                } else {
                    logger.info("已为新学生{}同步班级{}的作业分配", studentId, classId);
                }
            }
            return Result.success("注册成功");
        } catch (Exception e) {
            return Result.error("注册失败：" + e.getMessage());
        }
    }
} 